package com.springx.shiro;

import com.springx.shiro.domain.ShiroResource;
import com.springx.shiro.service.ShiroAccountService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.config.Ini;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.config.IniFilterChainResolverFactory;

import java.util.Iterator;
import java.util.List;

/**
 * Created by roman_000 on 2015/8/25.
 */
public class ShiroFilterCustomFactoryBean extends org.apache.shiro.spring.web.ShiroFilterFactoryBean {
    private ShiroAccountService shiroAccountService;

    @Override
    public void setFilterChainDefinitions(String definitions) {
        String allKey = "/**";
        Ini ini = new Ini();
        ini.load(definitions);
        Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
        List<ShiroResource> resourceList = this.shiroAccountService.findAllResource();
        if (!CollectionUtils.isEmpty(resourceList)) {
            String permissionType="perms";
            for (ShiroResource resource : resourceList) {
                if (StringUtils.isNotEmpty(resource.getPermissionKey()) && StringUtils.isNotEmpty(resource.getPermissionValue())) {
                    if(StringUtils.isNotEmpty(resource.getPermissionType())){
                        permissionType=resource.getPermissionType();
                    }
                    section.put(resource.getPermissionKey(),permissionType+"[\""+resource.getPermissionValue()+"\"]");
                }
            }
        }

        if (section.containsKey(allKey)) {
            section.put(allKey, section.remove(allKey));
        }
        setFilterChainDefinitionMap(section);
    }


    public void setShiroAccountService(ShiroAccountService shiroAccountService) {
        this.shiroAccountService = shiroAccountService;
    }
}
